﻿
Imports System.ComponentModel
Imports System.Runtime.InteropServices
Imports mshtml
Imports System.Threading


Public Class Form2

    <DllImport("winmm.dll")> _
    Public Shared Function waveOutGetVolume(h As IntPtr, ByRef dwVolume As UInteger) As Integer
    End Function

    <DllImport("winmm.dll")> _
    Public Shared Function waveOutSetVolume(h As IntPtr, dwVolume As UInteger) As Integer
    End Function

    sub New()

        ' 此调用是设计器所必需的。
        InitializeComponent()

        ' 在 InitializeComponent() 调用之后添加任何初始化。

        me.webBrowser1.AllowWebBrowserDrop = false
        CheckForIllegalCrossThreadCalls =false

        Dim nativeBrowser = DirectCast(webBrowser1.ActiveXInstance, SHDocVw.WebBrowser)

        AddHandler nativeBrowser.NewWindow2, AddressOf Form1_NewWindow2

        
    End Sub

    ’ 一次可以传递一个string
    Public Delegate Sub DataChangeHandler(sender As Object, args As DataChangeEventArgs)

    Public Event DataChange As DataChangeHandler

    Public  Property strcoursetime As String= "课程时长"

    Public  Property strlearn As String= "立即学习"
    Public  Property strtd As String= "td"
    Public  Property strtr As String= "tr"
    Property strbtn As String ="button"

    Property stra As String ="a"

    Property strli As String ="li"

    Property strdiv As String ="div"
    Property strp As String ="p"
    ''' <summary>
    ''' 页面
    ''' </summary>
    ''' <returns></returns>
    Public  Property doc As System.Windows.Forms.HTMLDocument
    public Property Clickelm As HtmlElement

    Property frm as Form2

    ''' <summary>
    ''' 课程时长
    ''' </summary>
    ''' <returns></returns>
    Public Property coursetime As Double

    public Property LastUrl As String

    Public Property csStartTime As System.DateTime

    Public Property csEndTime As System.DateTime

    Public Property csts As System.TimeSpan
    ''' <summary>
    ''' 网页加载状态
    ''' </summary>
    ''' <returns></returns>
    public Property loading As Boolean

    ''' <summary>
    ''' 计时器
    ''' </summary>
    ''' <returns></returns>
    Public Property objTimer As Timer
    ''' <summary>
    ''' 计时器是否在运行
    ''' </summary>
    ''' <returns></returns>
    Public Property IsTimerRun As Boolean = false
    ''' <summary>
    ''' 播放时间间隔
    ''' </summary>
    ''' <returns></returns>
    Public Property playtime as double =5

    ''' <summary>
    ''' 表示子窗口状态，true表示开启，false表示已关闭
    ''' </summary>
    ''' <returns></returns>
    public Property childWb as Boolean

    Private Sub Form1_NewWindow2(ByRef ppDisp As Object, ByRef Cancel As Boolean)
        frm=new Form2()
        '事先建好一个带WebBrowser的窗体
        ppDisp = frm.webBrowser1.ActiveXInstance
        AddHandler frm.DataChange, Addressof DataChanged
        frm.Text="视频窗口"
        frm.Show()

        frm.Visible = False

    End Sub


    Private Sub waitturninto()
        While(loading=true)
            Application.DoEvents()
        End While

    End Sub

    Private Sub WebBrowser1_Navigated(sender As Object, e As WebBrowserNavigatedEventArgs) Handles WebBrowser1.Navigated
        Try
            Dim vDocument As IHTMLDocument2 = DirectCast(webBrowser1.Document.DomDocument, IHTMLDocument2)
            vDocument.parentWindow.execScript("function confirm(str){return true;} ", "javascript")
            '弹出确认
            vDocument.parentWindow.execScript("function alert(str){return true;} ", "javaScript")
            '弹出提示
        Catch ex As Exception


        End Try
        '自动点击弹出确认或弹出提示

    End Sub

    Private Sub Form2_Shown(sender As Object, e As EventArgs) Handles Me.Shown
        

        '自动运行，如果是观看视频，

    End Sub



    
    Private sub Clickbutton(ByRef elm As HtmlElement) 
'        If ClickElmExist(Strlogin,strbtn) Then

        loading =true
        elm.InvokeMember("click")
        waitturninto()
      

    End sub

    Private sub ClickbuttonNew(ByRef elm As HtmlElement) 
'        If ClickElmExist(Strlogin,strbtn) Then
        elm.InvokeMember("click")

    End sub
    Public Sub OnDataChange(sender As Object, args As DataChangeEventArgs)

        RaiseEvent DataChange(Me, args)

    End Sub



    Private function ClickbuttonLogin() As Boolean
'        If ClickElmExist(Strlogin,strbtn) Then

        loading =true
        Clickelm.InvokeMember("click")
        waitturninto()
        Return true

'        Else
'            MessageBox.Show("未找到登录口，请检查网页")
'            Return false
'        End If

    End function

    Private function ClickElmExist(ByVal intext As string,ByVal elmstring As string) As Boolean


        Dim element2 As System.Windows.Forms.HtmlElementCollection = doc.GetElementsByTagName(elmstring)

        For Each elm As HtmlElement In element2
            If elm.InnerText =intext Then
                Clickelm=elm
                Return true
            End If
        Next

        Return false


    End Function



    Private Sub Form2_FormClosed(sender As Object, e As FormClosedEventArgs) Handles Me.FormClosed
        If IsTimerRun Then
            objTimer.Dispose()
        End If


        '        texthis(me.Text & "关闭",true)
        Try
            OnDataChange(Me, New DataChangeEventArgs("msg", Me.Text & "  " & "关闭"))
            OnDataChange(Me, New DataChangeEventArgs("closed", "closed now"))
        Catch ex As Exception

        End Try


    End Sub


    Private Sub texthis(ByVal msg As String, Optional islog As Boolean = False)
        Dim tim = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")

        Dim ms = tim & vbTab & vbTab & msg & vbCrLf

        OnDataChange(Me, New DataChangeEventArgs("msg", Me.Text & "  " & msg))
        '        if islog then
        '            log.WriteLog(ms)
        '        End If

        RichTextBox1.Text += ms

        '        RichTextBox1.SelectionStart = RichTextBox1.Text.Length
        '        RichTextBox1.ScrollToCaret()

    End Sub

    Private Sub WebBrowser1_DocumentCompleted(sender As Object, e As WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
        If WebBrowser1.ReadyState < WebBrowserReadyState.Complete Or WebBrowser1.Url.ToString() = LastUrl Then Return
        '自动点击弹出确认或弹出提示
        Dim vDocument As IHTMLDocument2 = DirectCast(WebBrowser1.Document.DomDocument, IHTMLDocument2)
        vDocument.parentWindow.execScript("function confirm(str){return true;} ", "javascript")
        '弹出确认
        vDocument.parentWindow.execScript("function alert(str){return true;} ", "javaScript")
        '弹出提示

        LastUrl = WebBrowser1.Url.ToString()
        loading = False

        autopick()


    End Sub

    Private Sub autopick()

        '判定是显示页面还是视频页面
        doc = WebBrowser1.Document

        If doc.Url.ToString().Contains("course/index") Then
            '若是课程页面

            If ClickElmExist(strcoursetime, strtd) Then

                '提取时间
                Dim allelm = Clickelm.Parent.GetElementsByTagName(strtd)
                For Each elm As HtmlElement In allelm
                    If elm.InnerText.Contains("分钟") Then
                        coursetime = CDbl(elm.InnerText.Split(New Char() {" "})(0))
                    End If
                Next

            End If

            texthis("视频窗口学习时间" & coursetime & "分钟", True)
            '          确定点击按钮,点击

            If ClickElmExist(strlearn, strbtn) Then
                ClickbuttonNew(Clickelm)
                '开启计时器
                csStartTime = System.DateTime.Now

                StartTimer(coursetime + 1.0)

                texthis("开启视频窗口学习课程", True)

                '开启状态
                childWb = True

            End If

        ElseIf doc.Url.ToString().Contains("study/container") Then
            '若是视频截面
            '修改js，加载页面

            texthis(" 已加载视频开始运行", True)

           

            csStartTime = System.DateTime.Now

            StartTimer2(playtime)
            
            Dim _savedVolume As UInteger
            waveOutGetVolume(IntPtr.Zero, _savedVolume)
            waveOutSetVolume(IntPtr.Zero, 0)
            '           dim srcall = doc.GetElementsByTagName("script")
            '            For Each src As HtmlElement In srcall
            '                RichTextBox1.Text+=src.InnerHtml+vbcrlf+vbCrLf
            '            Next
            '            texthis("已读取视频js")

        End If




    End Sub


    '数据变化事件
    Public Sub DataChanged(sender As Object, args As DataChangeEventArgs)

        '更新窗体控件

        If args.name = ("closed") Then
            csEndTime = System.DateTime.Now
            csts = csEndTime.Subtract(csStartTime)

            If csts.TotalSeconds < 300 and csts.TotalSeconds<coursetime*60 Then
                texthis("视频未学习完成课程，间隔时间" + csts.Seconds.ToString() + "秒", True)

            Else

                texthis("已经成功学习完成一门课程，子窗口已关闭", True)
                childWb = False
'                Me.disp()
                Me.Close()

            End If

        ElseIf args.name = ("msg") Then
            OnDataChange(Me, New DataChangeEventArgs("msg", args.pass))

        End If

    End Sub
    ''' <summary>
    ''' 用于视频播放信息
    ''' </summary>
    ''' <param name="timedelay"></param>
    Public Sub StartTimer2(ByVal timedelay As Double)
        Dim tcb As New TimerCallback(AddressOf Me.Playhis)
        '        Dim objTimer As Timer
        '5分钟记录一次
        objTimer = New Timer(tcb, Nothing, TimeSpan.FromMinutes(timedelay), TimeSpan.FromMinutes(timedelay))
        Dim _savedVolume As UInteger
        waveOutGetVolume(IntPtr.Zero, _savedVolume)
        waveOutSetVolume(IntPtr.Zero, 0)
        IsTimerRun = True

    End Sub


    Public Sub StartTimer(ByVal timedelay As Double)
        Dim tcb As New TimerCallback(AddressOf Me.TimerMethod)
        '        Dim objTimer As Timer

        objTimer = New Timer(tcb, Nothing, TimeSpan.FromMinutes(timedelay), TimeSpan.FromMinutes(2))
        IsTimerRun = True

    End Sub
    Public Sub TimerMethod(ByVal state As Object)
        '定时器，检查时间，如果已经到达计时则关闭子窗口
        '        MsgBox("The Timer invoked this method.")  

        If childWb = True Then
            '若时间间隔到了，已经开启页面未关闭，则强制关闭页面

            '            Me.disp()
            frm.Close()
            childWb = False
        End If


    End Sub
    ''' <summary>
    ''' 播放记录
    ''' </summary>
    ''' <param name="state"></param>
    Public Sub Playhis(ByVal state As Object)
        '定时器，记录历史到log
        '计算播放时间
        csEndTime = System.DateTime.Now
        csts = csEndTime.Subtract(csStartTime)

        texthis("已播放视频" & csts.Minutes.ToString() & "分钟，继续播放中", True)


    End Sub

    Private Sub Form2_Closing(sender As Object, e As CancelEventArgs) Handles Me.Closing

        Me.disp()

        If childWb = True Then
            '若时间间隔到了，已经开启页面未关闭，则强制关闭页面

            frm.Close()
            childWb = False
        End If


    End Sub

    Private Sub Form2_PreviewKeyDown(sender As Object, e As PreviewKeyDownEventArgs) Handles Me.PreviewKeyDown
        Dim _savedVolume As UInteger
        waveOutGetVolume(IntPtr.Zero, _savedVolume)
        ' restore the volume upon exit
        '        Me.FormClosing += Sub() waveOutSetVolume(IntPtr.Zero, _savedVolume)

        ' mute
        waveOutSetVolume(IntPtr.Zero, 0)


    End Sub

    Private Sub Form2_Load(sender As Object, e As EventArgs) Handles Me.Load
        Dim _savedVolume As UInteger
'        Me.disp()

        waveOutGetVolume(IntPtr.Zero, _savedVolume)
        ' restore the volume upon exit
        '        Me.FormClosing += Sub() waveOutSetVolume(IntPtr.Zero, _savedVolume)

        ' mute
        waveOutSetVolume(IntPtr.Zero, 0)

    End Sub

    Public Sub disp()
        if Me.WebBrowser1 IsNot Nothing
            Me.WebBrowser1.Url = Nothing
            Me.WebBrowser1.Document.OpenNew(False)
            Me.WebBrowser1 = Nothing
        End If
   
    End Sub


End Class